import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Select, Form, Timeline, Input, Button,DatePicker, TimePicker, Row, Col, message } from 'antd';
import { Line } from 'react-chartjs-2';
import travelUrl from '@/assets/images/travel.png';
import moment from 'moment';
import { userId } from '@/constant';
import Pie from './Pie'
import styles from './index.less'
const creator = (type, payload) => ({ type, payload });
const format='YYYY-MM-DD'
const LifeCycle = props => {
  const { dispatch } = props;
  const [pieVisible,setPieVisible]=useState(false)
  //默认查询当天
  useEffect(() => {
    const id = window.sessionStorage.getItem(userId);
    dispatch(creator('lifeCycle/getLifeData'));
  }, []);
  //键盘事件
  const onKeyDown = e => {
    if (e.keyCode === 13) {
      add();
    }
  };
  //查询
  const search = (id, date) => {
    const { dispatch } = props;
    dispatch(creator('lifeCycle/getLifeData', { id, date }));
  };
  //添加
  const add = () => {
    const { dispatch, form } = props;
    const id = window.sessionStorage.getItem(userId);
    form.validateFields((err, fields) => {
      if (!err) {
        const { start, end } = fields;
        fields.id = id;
        fields.comments = '';
        fields.date = moment(start).format('YYYY-MM-DD');
        if (moment(end).isBefore(start)) {
          message.warn('开始日期不可大于结束日期');
          return;
        }
        dispatch(creator('lifeCycle/addLifeData', fields)).then(res => {
          if (res.httpStatus === 200) {
            search(id);
            //清空输入框
            form.setFieldsValue({
              start: end,
              end: null,
              content: '',
            });
          } else {
            message.warn('添加出错');
          }
        });
      }
    });
  };
  //显示饼状图
  const togglePie=()=>{
    setPieVisible(!pieVisible)
  }
  const { getFieldDecorator } = props.form;
  const { lifeCycleData } = props.lifeCycle;
  return (
    <div className={styles.container}>
    <Form layout="inline">
      <Row style={{marginBottom:15}}>
        <img src={travelUrl} style={{ width: 38, marginRight: 10 }} />
        <span>人生轨迹</span>
      </Row>
      <Row style={{ height: 60 }}>
        <Form.Item>
          {getFieldDecorator('start', {
            rules: [
              {
                required: true,
                message: '请选择开始日期',
              },
            ],
          })(<DatePicker placeholder="请选择开始日期" style={{ width: 150 }} format={format}/>)}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('end', {
            rules: [
              {
                required: true,
                message: '请选择结束日期',
              },
            ],
          })(<DatePicker placeholder="请选择结束日期" style={{ width: 150 }} format={format}/>)}
        </Form.Item>
      </Row>

      <Form.Item>
        {getFieldDecorator('content', {
          rules: [
            {
              required: true,
              message: '请输入事项',
            },
          ],
        })(
          <Input
            style={{ width: 230, marginRight: 5 }}
            placeholder="请输入事项"
            onKeyDown={onKeyDown}
          />,
        )}
      </Form.Item>
      <Form.Item style={{marginBottom:15}}>
        <Button type="primary" onClick={add}>
          添加
        </Button>
      </Form.Item>
      <Form.Item style={{display:lifeCycleData.length?'inline-block':'none'}}>
        <Button type="primary" onClick={togglePie}>生成饼状图</Button>
      </Form.Item>
      <Timeline>
        {lifeCycleData.map(item => (
          <Timeline.Item key={item._id}>{`${moment(item.start).format(format)}-${moment(item.end).format(format)} ${item.content}`}</Timeline.Item>
        ))}
      </Timeline>
      {/* 饼状图 */}
      <Pie pieVisible={pieVisible} togglePie={togglePie} lifeCycleData={lifeCycleData}/>
    </Form>
    </div>
  );
};

const WrappedLifeCycle = Form.create({ name: 'diary' })(LifeCycle);

export default connect(({ lifeCycle }) => ({ lifeCycle }))(WrappedLifeCycle);
